package com.sugon.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**
 * RSA非对称加密工具类
 *
 * @Author YuXD
 * @Version 1.0
 * @since 2022/3/29
 */
public class RsaUtil {

    /**
     * RSA私钥
     */
    private static String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM966sFShT0hdSm7" +
            "pVJycdEP8Bgp/t2yoWQT2jS8Bva8JOyMhb6TSxp1vy2Efxt7BQVbh6PMrwlGq6Ej" +
            "4xpcTDV2OnpOGWc4MeERcOhFeut43hBvuHp3XasyD23HlUDbJ4cHMOsXWe0JapF+" +
            "RdrnNLxp+ovnkrlecOc6Me38AXiRAgMBAAECgYEAh4LMmP+ArnCPyXYZgEPnOpii" +
            "Q+YJ5FqrNmYQ+qhkE/rGUwlkwRgK0XleKCiFrDkpClrBuKYTHIffyRtbVPg7fPJp" +
            "pMs+DADRwdgQr2rWSGVrwJkHhceugCdZ0oCQ8h+eASdoxu6TE4zSH3bq9oj4lv8D" +
            "Cc2QEVccn7VMmrN+B1ECQQDp0qtcdvctMYOYUhmRas8Zqx+aqN2063KRCr6ZhAkF" +
            "ipiBWaKCCKZm3P2lwV0ZLQxBakz2OGBGmbxgjhvAQC8vAkEA4yih6l5t2U2GWLzG" +
            "Kmx7a3JZOkEp+1VY3bkZt/yUlJ0L9qyXRRd3GoRRT0fcos5wye+S+w3xzGxn9j/9" +
            "lNDkPwJAa8TbkmyKlFvj6Uq92hY+ifgjQudd+EskrNEk9CC0/8bXb5bencxa1cI5" +
            "bjJnNHlc0rGp8zocta2Z827MP5nVpQJAAeAK/iFLbNjL/B2K0TzWA/wMqoNxMkbx" +
            "Fdt6T9+A5n0pZR7lnMdlz006Upo4QwvLOI+GuhXSYiqe7RR4JmtXBwJAHkMo+d9v" +
            "6yIj/EAHml7rEYLshdr8DwS+cXo+dwK/mi6+ds8C5Axqpn2VssmDT/IbUcwjfJee" +
            "gOPsnYRweFiDdA==";

    /**
     * RSA公钥
     */
    private static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPeurBUoU9IXUpu6VScnHRD/AY" +
            "Kf7dsqFkE9o0vAb2vCTsjIW+k0sadb8thH8bewUFW4ejzK8JRquhI+MaXEw1djp6" +
            "ThlnODHhEXDoRXrreN4Qb7h6d12rMg9tx5VA2yeHBzDrF1ntCWqRfkXa5zS8afqL" +
            "55K5XnDnOjHt/AF4kQIDAQAB";

    /**
     * RSA实例
     */
    private static RSA rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);

    /**
     * 公钥加密
     *
     * @param encryptContent
     * @return
     */
    public static String encryptWithPublicKey(String encryptContent) {
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(encryptContent, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);

        return Base64.encode(encrypt);
    }

    /**
     * 私钥解密
     *
     * @param decryptContent
     * @return
     */
    public static String decryptWithPrivateKey(String decryptContent) {
        try {
            byte[] decrypt = rsa.decrypt(Base64.decode(decryptContent), KeyType.PrivateKey);
            return new String(decrypt);
        } catch (Exception ex) {

        }
        return null;
    }

}
